/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.User;
import bc.util.HibernateUtil;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.hibernate.Query;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class Mail {
    private org.hibernate.Session session;
    public Mail(){
        SessionFactory factory = HibernateUtil.getSessionFactory();
        this.session = factory.getCurrentSession();
    }
    public void send(String smtpServer, String to, String from, String psw, String subject, String body) throws Exception {

        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");
        final String login = from;
        final String pwd = psw;
        Authenticator pa = null;
        if (login != null && pwd != null) {
            props.put("mail.smtp.auth", "true");
            pa = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(login, pwd);
                }
            };
        }//else: no authentication
        Session session = Session.getInstance(props, pa);
// — Create a new message –
        Message msg = new MimeMessage(session);
// — Set the FROM and TO fields –
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
                to, false));

// — Set the subject and body text –
        msg.setSubject(subject);

        msg.setText(body);//Để gởi nội dung dạng utf-8 các bạn dùng msg.setContent(body, "text/html; charset=UTF-8");
// — Set some other header information –
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setContent(body, "text/html; charset=UTF-8");
        msg.setSentDate(new Date());
        msg.saveChanges();
// — Send the message –
        Transport.send(msg);
        System.out.println("Mail da duoc gui");

    }
    public void update(String email, String newpass){
        try{
            session.getTransaction().begin();
            String sql="from User where email = ? ";
            Query query=session.createQuery(sql);
            query.setString(0, email);
            User result=(User)query.uniqueResult();
                result.setPassword(newpass);
                session.update(result);
                session.flush();
                session.getTransaction().commit(); 
        }catch(Exception e){
        if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    // kiem tra ton tai email
    public boolean authenticate(String email){
        try{
            session.getTransaction().begin();
            String sql="from User where email = ? ";
            Query query=session.createQuery(sql);
            query.setString(0, email);
            User result=(User)query.uniqueResult();
            session.flush();
            session.getTransaction().commit();
            if(result!=null){
                return true;
            }else return false;
            
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return false;
    }
    private String input ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   public String next(int length) {
        String string = new String();
        final int max = input.length();
        for(int i=0; i<length; i++) {
            string += input.charAt(((int)(Math.random()*1000)) % max);
        }
        return string;
   }
   /* public static void main(String[] args) {
        Mail A=new Mail();
        String str=A.next(15);
        System.out.println(str);
    }
*/
  /*  public static void main(String[] args) {
         Mail A=new Mail();
         A.update("ninjaninjan@gmail.com", "CZQKN5774E2P0FX");
    }
*/
  /*  public static void main(String[] args) throws Exception {
        Mail A = new Mail();
        String smtpServer = "smtp.gmail.com";
        String to = "ninjaninjan@gmail.com";
        String from = "supporbconline.uit@gmail.com";
        String psw = "huyennga123";
        String subject = "support";
        String body = "abc";
        A.send(smtpServer, to, from, psw, subject, body);

    }
    */
}
